#include <iostream>
#include <vector>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <stdio.h>

std::vector<int> data;

enum{
    OK=0,
    OPEN_FILE_ERROR,
};

int SaveData(){
    std::string name = std::to_string(time(nullptr));
    name += ".txt";    
    FILE* f = fopen(name.c_str(), "w");
    if(f == nullptr) return OPEN_FILE_ERROR;
    std::string datastr;
    for(auto d : data){
	datastr += std::to_string(d);
	datastr += " ";
    }
    fputs(datastr.c_str(), f);
    fclose(f);
    return OK; 
}

void Save(){
    pid_t id = fork();
    //子进程
    if(id == 0){
	int exit_code = SaveData();
        exit(exit_code);
    }
    
    //父进程，什么都不做，回收子进程的僵尸状态即可
    else{
	int status = 0;
	pid_t rid = waitpid(id, &status, 0);
	//等待子进程成功
	if(rid > 0){
	    printf("waiting subprocess successfully!\n");
	    //查看子进程的退出状态
	    if(WIFEXITED(status)){
		//子进程成功退出
		printf("subprocess exit successfully! rid:%d, exit_code:%d\n", rid, WEXITSTATUS(status));
	    }
            else{
		//子进程退出失败
		printf("something wrong in subprocess exit!\n");
	    }
    	}
	//等待子进程失败
	else{
	    printf("something wrong in waiting subprocess!\n");
	}
    }
}

int main(){
    int count = 1;
    while(true){
	data.push_back(count++);
	sleep(1);
	
	//每隔10秒让子进程拷贝一份数据
	if(count % 10 == 0){
	    Save();
	}
    }
    return 0;
}
